package com.party.web.web.controller.user;

import com.party.common.constant.Constant;
import com.party.common.redis.StringJedis;
import com.party.common.utils.PasswordUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.YesNoStatus;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.member.MemberGroupInfo;
import com.party.core.model.partner.MemberPartner;
import com.party.core.model.sign.MemberSign;
import com.party.core.model.system.MemberSysRole;
import com.party.core.model.system.RoleEnum;
import com.party.core.model.system.RoleType;
import com.party.core.model.system.SysRole;
import com.party.core.service.member.IMemberGroupInfoService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.notify.IMemberSetService;
import com.party.core.service.partner.IMemberPartnerService;
import com.party.core.service.partner.biz.MemberPartnerBizService;
import com.party.core.service.sign.IMemberSignService;
import com.party.core.service.system.IMemberSysRoleService;
import com.party.core.service.system.ISysRoleService;
import com.party.web.utils.RealmUtils;
import com.party.web.biz.system.member.MemberGroupBizService;
import com.party.web.web.dto.AjaxResult;
import com.party.web.web.dto.input.user.RegisterInput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @program: party
 * @description: 注册控制器
 * @author: Hua Qunhao
 * @create: 2019-05-22 15:18
 **/
@Controller
@RequestMapping(value = "user/register")
public class RegisterController {

    protected static Logger logger = LoggerFactory.getLogger(RegisterController.class);

    @Autowired
    private StringJedis stringJedis;

    @Autowired
    private IMemberGroupService memberGroupService;

    @Autowired
    private MemberGroupBizService memberGroupBizService;

    @Autowired
    private IMemberSetService memberSetService;

    @Autowired
    private IMemberSignService memberSignService;

    @Autowired
    private IMemberGroupInfoService memberGroupInfoService;

    @Autowired
    private IMemberPartnerService memberPartnerService;

    @Autowired
    private IMemberSysRoleService memberSysRoleService;

    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private MemberPartnerBizService memberPartnerBizService;

    /**
     * 用户注册
     *
     * @param registerInput
     * @param result
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/partnerRegister")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult register(@Validated RegisterInput registerInput, BindingResult result, HttpServletRequest request) {
        //数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErros = result.getAllErrors();
            return AjaxResult.error(allErros.get(0).getDefaultMessage());
        }

        List<MemberGroup> mobile = null;
        mobile = memberGroupService.checkUserName("username", registerInput.getUsernameRg(), "", Constant.MEMBER_ORGANIZATION);
        if (mobile != null && mobile.size() > 0) {
            return AjaxResult.error("登录名已存在");
        }

        String oldMemberId = null;
        mobile = memberGroupService.checkUserName("mobile", registerInput.getMobileRg(), "", Constant.MEMBER_ORGANIZATION);
        if (mobile != null && mobile.size() > 0) {
            if (mobile.size() == 1) {
                boolean hasPartner = sysRoleService.hasRole(mobile.get(0).getId(), RoleEnum.PARTNER_ROLE.getCode());
                if (hasPartner) {
                    return AjaxResult.error("手机号已存在");
                } else {
                    oldMemberId = mobile.get(0).getId();
                }
            } else {
                return AjaxResult.error("手机号已存在");
            }
        }

        //验证验证码是否一致
        String code = stringJedis.getValue(registerInput.getMobileRg());
        if (code == null || !code.equals(registerInput.getVerifyCodeRg())) {
            return AjaxResult.error("手机号验证码不一致");
        }
        try {
            MemberGroup insertMember = new MemberGroup();
            insertMember.setId(oldMemberId);
            insertMember.setMobile(registerInput.getMobileRg());
            insertMember.setUsername(registerInput.getUsernameRg());
            insertMember.setIsPartner(YesNoStatus.YES.getCode());
            insertMember.setPassword(PasswordUtils.encryptPassword(registerInput.getPasswordRg()));

            //保存用户
            MemberGroup dbMember = memberGroupBizService.saveOrupdatePartnerMember(insertMember);

            //分配系统角色
            SysRole sysRole = sysRoleService.getRole(RoleEnum.PARTNER_ROLE.getCode(), RoleType.SYSTEM_ROLE.getCode());
            MemberSysRole memberSysRole = new MemberSysRole(dbMember.getId(), sysRole.getId());
            List<MemberSysRole> msr = memberSysRoleService.list(memberSysRole);
            if (msr.size() == 0) {
                memberSysRoleService.insert(memberSysRole);
            }

            // 保存合作商附属信息表
            MemberPartner memberPartner = memberPartnerService.findByMemberId(dbMember.getId());
            if (null == memberPartner) {
                memberPartner = new MemberPartner();
            }
            memberPartner.setMemberId(dbMember.getId());
            memberPartner.setPartnerType(MemberPartner.PARTNER_TYPE_REGISTER);
            memberPartner.setUpdateBy(dbMember.getId());
            memberPartner.setCreateBy(dbMember.getId());
            if (StringUtils.isEmpty(memberPartner.getId())) {
                memberPartnerService.insert(memberPartner);
            } else {
                memberPartnerService.update(memberPartner);
                memberPartnerBizService.saveOrUpdateChildMemberPartner(memberPartner);
            }

            // 保存组织机构信息
            MemberGroupInfo memberGroupInfo = memberGroupInfoService.findByMemberId(dbMember.getId());
            if (null == memberGroupInfo) {
                memberGroupInfo = new MemberGroupInfo();
            }
            memberGroupInfo.setMemberId(dbMember.getId());
            memberGroupInfo.setCustomerPhone(dbMember.getMobile());
            memberGroupInfo.setWithdrawalCharge(0.02d);
            memberGroupInfo.setIsEditInfo(YesNoStatus.NO.getCode());
            if (StringUtils.isEmpty(memberGroupInfo.getId())) {
                memberGroupInfoService.insert(memberGroupInfo);
            } else {
                memberGroupInfoService.update(memberGroupInfo);
            }

            //保存用户信息设置
            memberSetService.initMemberSet(dbMember.getId());

            //保存合作商附属表  机构app签到
            memberSignService.getSet(dbMember.getId());
        } catch (Exception e) {
            logger.error("合作商注册异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("注册异常");
        }
        return AjaxResult.success();
    }

    /**
     * 编辑
     * @param member
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updatePartnerMember")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult updatePartnerMember(MemberGroup member, HttpServletRequest request) {
        if(member==null ||StringUtils.isEmpty(member.getLogo())){
            return AjaxResult.error("请上传头像");
        }
        if(member==null ||StringUtils.isEmpty(member.getRealname())){
            return AjaxResult.error("昵称不能为空");
        }
        String memberId = RealmUtils.getCurrentUser().getId();
        if(StringUtils.isEmpty(memberId)){
            return AjaxResult.error("账号设置异常");
        }
        try {
            member.setId(memberId);
            MemberGroup dbMember = memberGroupBizService.saveOrupdatePartnerMember(member);

            MemberGroupInfo memberGroupInfo = memberGroupInfoService.findByMemberId(dbMember.getId());
            memberGroupInfo.setIsEditInfo(YesNoStatus.YES.getCode());
            memberGroupInfoService.update(memberGroupInfo);

        } catch (Exception e) {
            logger.error("账号设置异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("账号设置异常");
        }
        return AjaxResult.success("账号设置成功");
    }
}
